package com.zwt.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwt.annotation.NoAuthAnnotation;
import com.zwt.constant.RedisConstant;
import com.zwt.constant.RedisKeyUtil;
import com.zwt.model.TAccountUser;
import com.zwt.model.UserInfo;
import com.zwt.redis.Redis;
import com.zwt.result.ResultBean;
import com.zwt.result.ResultCode;
import com.zwt.service.TAccountUserService;
import com.zwt.util.TRegular;
import com.zwt.util.TTime;
import com.zwt.util.token.TokenUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Created by zwt on 2018/9/6.
 */
@RestController
@RequestMapping("/baseServer/login")
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private TAccountUserService tAccountUserService;

    @Autowired
    private Redis redis;

    /**
     * 登录
     * @param phone
     * @param code
     * @return
     */
    @RequestMapping("login")
    public ResultBean<JSONObject> login(@RequestParam String phone,@RequestParam String code){
        ResultBean<JSONObject> result = new ResultBean<>();
        JSONObject data = new JSONObject();
        if(StringUtils.isBlank(phone)){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号为空");
            result.setMessage("手机号不能为空!");
            return result;
        }
        if (!TRegular.validatePhone(phone)) {
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"手机号码格式错误");
            result.setMessage("手机号码格式错误!");
            return result;
        }
        if (!phone.equals("15901280519") && !phone.equals("18888888888")) {
            //redis中获取验证码
            String redisCode = redis.get(RedisKeyUtil.getRegCache(phone), String.class);
            if (StringUtils.isBlank(redisCode)) {
                logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                        TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"验证码已失效");
                result.setMessage("验证码已失效!");
                return result;
            }
            if (!code.trim().equals(redisCode)) {
                logger.error("用户手机号: {}, 注册时间: {}, 注册失败, 失败原因: {}",phone,
                        TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"验证码错误");
                result.setMessage("验证码错误, 请检查!");
                return result;
            }
        }
        TAccountUser tAccountUser = tAccountUserService.selectByPhone(phone);
        if(null==tAccountUser){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"该手机号不存在");
            result.setMessage("该手机号不存在!");
            return result;
        }
        Byte userStatus = tAccountUser.getUserStatus();
        if(null==userStatus){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"tAccountUser.getUserStatus()==null");
            result.setMessage("该账号不存在!");
            return result;
        }
        if(ObjectUtils.equals(userStatus.intValue(),0)){
            logger.error("用户手机号: {}, 登录时间: {}, 登录失败, 失败原因: {}",phone,
                    TTime.parseStringFromDate(new Date(), TTime.SIMPLE_DATEFORMAT3),"tAccountUser.getUserStatus()==0");
            result.setMessage("该账号被禁用!");
            return result;
        }
        //将用户信息放入redis 两个月有效期
        String token = TokenUtil.getToken(phone);
        UserInfo userInfo = new UserInfo();
        userInfo.settAccountUser(tAccountUser);
        redis.set(token,UserInfo.class, RedisConstant.MONTH_1*2);
        data.put("token",token);
        data.put("userInfo",userInfo);
        result.setData(data);
        result.setResultCode(ResultCode.SUCCESS.getCode());
        return result;
    }

    /**
     * token失效 或不传时 拦截器拦截进入该接口 客户端接收401 跳转登录页
     * @return
     */
    @RequestMapping("fail")
    public ResultBean<JSONObject> fail(){
        ResultBean<JSONObject> result = new ResultBean<>();
        result.setResultCode(ResultCode.UNAUTHORIZED.getCode());
        result.setMessage("用户未登录或无权限访问, 请登录后重试, 谢谢");
        return result;
    }
}
